﻿#include "tcpserver.h"

FuTcpServer *FuTcpServer::fuTcpServer = nullptr;
FuTcpServer::FuTcpServer(QObject *parent) : QObject(parent)
{
    initServer();
}

FuTcpServer *FuTcpServer::getTcpServer()
{
    if(fuTcpServer == NULL)
        fuTcpServer = new FuTcpServer;
    return fuTcpServer;
}

void FuTcpServer::initServer()
{
    //创建服务器并开始监听
    server = new QTcpServer(this);
    if(!server->listen(QHostAddress(ip),port))
    {
        QMessageBox::critical(nullptr,"错误","监听失败，检查ip或端口是否有误");
        return;
    }
    //处理新连接的信号
    connect(server,&QTcpServer::newConnection,this,&FuTcpServer::slot_newConnection);
}

void FuTcpServer::slot_newConnection()
{
    socket = server->nextPendingConnection();
    connect(socket,&QTcpSocket::readyRead,this,&FuTcpServer::signal_readData);
    connect(socket,&QTcpSocket::disconnected,this,&FuTcpServer::slot_closeConnection);
    //发送signal_connect信号表示已连接
    emit signal_connect(true);
}

void FuTcpServer::slot_closeConnection()
{
    //删除对象
    socket->deleteLater();
    //设置为空指针
    socket = nullptr;
    //发送signal_connect信号表示断开连接
    emit signal_connect(false);
}
